<!-- #layout name=default -->
<div id="main" class="offset-top" v-cloak>
  <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="page-header">
          <h1 class="title">Import a site</h1>
        </div>
        <kb-form
          simple
          class="form-horizontal"
          :model="model"
          :rules="rules"
          ref="form"
        >
          <div class="note note-info">
            <p>{{Kooboo.text.site.sites.importTip}}</p>
          </div>
          <kb-form-item class="form-group" prop="siteName" v-slot="error">
            <div :class="{'has-error' : !!error.error}">
              <label class="col-md-2 control-label" for="SiteName"
                >Site name</label
              >
              <div class="col-md-10">
                <input
                  class="input-medium form-control"
                  placeholder="Site name"
                  type="text"
                  v-model="model.siteName"
                  v-kb-tooltip:right.manual.error="error.error"
                />
                <span class="help-block"
                  >Start with letters and no space allowed</span
                >
              </div>
            </div>
          </kb-form-item>
          <kb-form-item class="form-group" prop="subDomain" v-slot="error">
            <div :class="{'has-error' : !!error.error}">
              <label class="col-md-2 control-label" for="SubDomain"
                >Domain</label
              >
              <div class="col-md-10">
                <div class="form-inline">
                  <input
                    class="input-medium form-control"
                    id="SubDomain"
                    name="SubDomain"
                    placeholder="SubDomain"
                    type="text"
                    v-model="model.subDomain"
                  />
                  <select
                    class="form-control"
                    v-model="model.rootDomain"
                    v-kb-tooltip:right.manual.error="error.error"
                  >
                    <option
                      v-for="($data,index) in domains"
                      :key="index"
                      :value="$data.domainName"
                      >{{'.'+$data.domainName}}</option
                    >
                  </select>
                </div>
                <span class="help-block"
                  >{{ Kooboo.text.info.subDomainInfo}}</span
                >
              </div>
            </div>
          </kb-form-item>
          <kb-form-item class="form-group" prop="file" v-slot="error">
            <div :class="{'has-error' : !!error.error}">
              <label class="col-md-2 control-label" for="Package"
                >Package</label
              >
              <div class="col-md-10">
                <div
                  class="well"
                  id="dropArea"
                  style="border: 1px dashed #9a9a9a"
                  v-show="showDropArea"
                >
                  <h4 class="text-center">Drop here</h4>
                </div>

                <div class="fileinput fileinput-new">
                  <span class="btn btn-default btn-file">
                    {{model.file?Kooboo.text.common.change:Kooboo.text.common.selectFile}}
                    <input
                      type="file"
                      name="package"
                      v-kb-upload="{
                    allowMultiple: false,
                    acceptTypes: ['application/zip'],
                    acceptSuffix: ['zip'],
                    callback: uploadFile
                }"
                    />
                  </span>
                  &nbsp;<span
                    v-if="ableToDragFile&&!model.file"
                    v-kb-tooltip:right.manual.error="error.error"
                    >or drag zip file here.</span
                  >
                  <span v-if="model.file" class="fileinput-filename"
                    >{{model.file.name}}</span
                  >
                  <a v-if="model.file" @click="removeFile" class="close"
                    ><i class="fa fa-close"></i
                  ></a>
                  <span class="help-block">Accept type: *.zip</span>
                </div>
              </div>
            </div>
          </kb-form-item>
          <ul class="pager">
            <li class="next"
              ><button class="btn blue" @click="startSubmit">Start</button></li
            >
            <li class="previous"
              ><a @click.stop="SPAClick" class="btn gray">Return</a></li
            >
          </ul>
        </kb-form>

        <kb-upload-progressor
          v-if="importing"
          :percentage="uploadPercentage"
        ></kb-upload-progressor>
      </div>
    </div>
  </div>
</div>
<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/SPA.js",
      "/_Admin/Scripts/components/kbForm.js",
      "/_Admin/Scripts/components/kbUploadProgressor.js"
    ]);
  })();

  var self = new Vue({
    el: "#main",
    data: function() {
      var self = this;
      return {
        model: {
          siteName: "",
          subDomain: "",
          rootDomain: "",
          file: null
        },
        rules: {
          siteName: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[A-Za-z][\w\-]*$/,
              message: Kooboo.text.validation.siteNameInvalid
            },
            {
              remote: {
                url: Kooboo.Site.isUniqueName(),
                data: function() {
                  return {
                    SiteName: self.model.siteName
                  };
                }
              },
              message: Kooboo.text.validation.taken
            }
          ],
          subDomain: [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^[A-Za-z][\w\-]*$/,
              message: Kooboo.text.validation.siteNameInvalid
            },
            {
              min: 1,
              max: 63,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                63
            },
            {
              remote: {
                url: Kooboo.Site.CheckDomainBindingAvailable(),
                data: function() {
                  return {
                    SubDomain: self.model.subDomain,
                    RootDomain: self.model.rootDomain
                  };
                }
              },
              message: Kooboo.text.validation.taken
            }
          ],
          file: [{ required: Kooboo.text.validation.required }]
        },
        domains: [],
        showDropArea: false,
        ableToDragFile: false,
        uploadPercentage: 0,
        importing: false
      };
    },
    mounted: function() {
      var self = this;
      $.when(Kooboo.Domain.getAvailable()).then(function(availRes) {
        if (availRes.success) {
          self.domains = availRes.model;
          if (self.domains.length) {
            self.model.rootDomain = self.domains[0].domainName;
          }
        }
      });
      if (typeof Worker !== undefined) {
        self.ableToDragFile = true;

        $(document).on({
          dragleave: _.debounce(function(e) {
            e.preventDefault();
            self.showDropArea = false;
          }, 500),
          dragenter: function(e) {
            e.preventDefault();
            self.showDropArea = true;
          },
          dragover: function(e) {
            e.preventDefault();
            self.showDropArea = true;
          },
          drop: function(e) {
            e.preventDefault();
            self.showDropArea = false;
          }
        });

        var box = document.getElementById("dropArea");
        box.addEventListener("drop", function(e) {
          e.preventDefault();

          var files = e.dataTransfer.files;

          if (files.length) {
            var name = files[0].name;
            if (
              name.indexOf(".") > -1 &&
              name.split(".").reverse()[0] == "zip"
            ) {
              self.model.file = files[0];
              if (!self.model.siteName) {
                var arr = name.split(".");
                arr.pop();
                self.model.siteName = arr.join(".");
              }
            } else {
              alert(Kooboo.text.alert.uploadZipFile);
            }
          }
        });
      }
    },
    methods: {
      removeFile: function() {
        self.model.file = null;
        self.model.siteName = "";
      },
      startSubmit: function() {
        if (self.$refs.form.validate()) {
          self.importing = true;
          var data = new FormData();
          data.append("SiteName", self.model.siteName);
          data.append("SubDomain", self.model.subDomain);
          data.append("RootDomain", self.model.rootDomain);
          data.append("Package", self.model.file);
          Kooboo.Site.Import(data, function(rate) {
            self.uploadPercentage = rate;
          }).then(function(res) {
            if (res.success) {
              location.href = Kooboo.Route.Get(Kooboo.Route.Site.DetailPage, {
                SiteId: res.model
              });
            }
          });
        }
      },
      SPAClick: function() {
        self.$refs.form.clearValid();
        self.$nextTick(function() {
          Kooboo.SPA.getView(Kooboo.Route.Site.ListPage, {
            container: '[layout="default"]'
          });
        });
      },
      uploadFile: function(data, files) {
        self.model.file = files[0];

        if(!self.model.siteName){
          self.model.siteName = files[0].name.split(".zip")[0];
        }
      }
    },
    watch: {
      "model.siteName": function(value) {
        self.model.subDomain = value;
      }
    }
  });
</script>
